<div class="layui-fluid">
    <!--搜索条-->
    <div class="layui-form-item" style="margin-top:10px">
        <form action="#" class="layui-form" align="center" >
            <div class="layui-form-item">
                邮箱：
                <div class="layui-inline">
                    <input type="text" name="email" autocomplete="off" placeholder="请输入邮箱" class="layui-input">
                </div>
                状态：
                <div class="layui-inline">
                    <select name="status">
                        <option value="-1">请选择</option>
                        <option value="0">无效</option>
                        <option value="1">有效</option>
                    </select>
                </div>
                <div class="layui-inline">
                    <button class="layui-btn layui-btn-radius layui-icon layui-icon-search" lay-submit lay-filter="search">
                        搜索
                    </button>
                </div>
            </div>
        </form>
    </div>
    <!--添加弹出层-->
    <div class="layui-form-item">
        <table id="demo" lay-filter="test" ></table>
        <!--左上角的添加和删除-->
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm layui-icon layui-icon-addition" lay-event="insert">添加</button>
                <button class="layui-btn layui-btn-danger layui-btn-sm layui-icon layui-icon-delete" lay-event="delete">删除</button>
            </div>
        </script>
        <!-- 表中的编辑和授权 -->
        <script type="text/html" id="barDemo">
            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
            <a class="layui-btn layui-bg-blue layui-btn-xs" lay-event="give">授权</a>
        </script>


        <script>
            layui.use(['table', 'form','layer'], function () {
                var table = layui.table;
                var form = layui.form;
                //第一个实例
                form.render()
                //渲染表格
                table.render({
                    elem: '#demo'
                    , height: 350
                    , weight: 750
                    , toolbar: "#toolbarDemo"
                    , url: '/queryAdminUsers' //数据接口
                    , page: true //开启分页
                    , cols: [[ //表头
                        {type: 'checkbox', fixed: 'left'}//获取最前面的勾中框
                        ,{field: 'id', title: 'ID', width: 60, sort: true, fixed: 'left'}
                        , {field: 'password', title: '密码', width: 130}
                        , {field: 'email', title: '邮箱', width: 100}
                        , {field: 'real_name', title: '真实姓名', width: 130}
                        , {
                            field: 'status', title: '状态', width: 110, templet: function (data) {
                                if (data.status == 1) {
                                    return '<span class="layui-badge layui-bg-green">有效</span>'
                                }
                                return '<span class="layui-badge layui-bg-gray">无效</span>'
                            }
                        }
                        , {field: "right", title: "操作", toolbar: '#barDemo', width: 130}
                    ]]
                    , page: {
                        limit: 2//每页显示5条
                        , first: '首页' //首页显示文字，默认显示页号
                        , last: '尾页'
                        , prev: '<<' //上一页显示内容，默认显示 > <
                        , next: '>>'
                        , limits: [1, 2, 3]
                        , layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布
                    },
                });
                //编辑  找到表中的lay-event为多少的操作
                table.on('tool(test)', function (msg) {
                    switch (msg.event) {
                        case'edit':
                            //layerIndex:整个弹出层得对象
                            layerIndex = layer.open({
                                type:1,// Page层类型
                                area:['500px','330px'],
                                title:["更新用户","padding-left:5px"], // 标题，及标题样式
                                content:layui.$("#insertUserForm"), // id为insertUserForm的div的弹窗
                                shade:false //是否遮罩
                            })
                            var flag = msg.data;//获取当前行所有数据
                            // 【1】data是一个js对象
                            var data = form.val("returnForm",flag);//在lay-filter为returnForm的表单中，回显数据flag,而且是一个js对象
                            console.log(data);//此时是修改之前的数据
                            //编辑
                            form.on("submit(addUserOk)",function (data) {
                                console.log(data.field);//获取表单中的所有内容  此时是修改之后的内容
                                $.ajax({
                                    url:"/updateUser",
                                    type:"put",
                                    // 【2】 会将js对象转换为json串，此时需要配合  application/json  controller层需要用@RequestBody将json字符串转换为对象
                                    data:JSON.stringify(data.field),
                                    //【3】 会将js对象 data转换为 url参数 xx=xx&xxx=xx&xxx=xxx....
                                    // data:data,
                                    contentType:"application/json",
                                    success:function (msg) {
                                        if(msg){
                                            layer.alert("修改成功")
                                        }else {
                                            layer.alert("修改失败")
                                        }
                                        layer.close(layerIndex)//提交之后关闭弹出层
                                        table.reload("demo")//刷新表单
                                        $("#insertForm")[0].reset();//清空弹窗
                                        return false;//关闭表单提交
                                    }
                                })
                            });
                            break;
                        case 'give':
                            //layerIndex:整个弹出层得对象
                            layerIndex = layer.open({
                                type:1,// Page层类型
                                area:['400px','300'],
                                title:["授权管理","padding-left:5px"], // 标题，及标题样式
                                content:layui.$("#giveRoleForm"), // id为giveRoleForm的div的弹窗
                                shade:false //是否遮罩
                            });
                            //回显数据 $.ajax();
                            $.ajax({
                                url:"/queryRoleVO",
                                type:"get",
                                data:"userId="+msg.data.id,
                                success:function (ret) {
                                    console.log(ret);
                                    //在表单的id输入框中，添加一个userId
                                    $("#userId_updateRole").val(msg.data.id)
                                    //清空所有拼接记录
                                    $("#forEachRoles").empty();
                                    //遍历ret.roles显示所有角色
                                    for (var i = 0; i < ret.roles.length; i++) {
                                        if(ret.userRoles.indexOf(ret.roles[i].id)!=-1){
                                            $("#forEachRoles").append('<input type="checkbox" name="roleId" checked value="'+ret.roles[i].id +'"title="'+ret.roles[i].remark +'"> <br>');
                                        }else {
                                            $("#forEachRoles").append('<input type="checkbox" name="roleId" value="'+ret.roles[i].id +'"title="'+ret.roles[i].remark +'"><br>');
                                        }
                                    }
                                    form.render();
                                }
                            });
                            break;
                    }
                });
                //删除 添加
                table.on('toolbar(test)', function (data) {
                    switch (data.event) {
                        case 'delete':
                            layer.msg("删除");
                            var checkStatus = table.checkStatus('demo');
                            console.log(checkStatus.data) //获取选中行的数据
                            var ids = [];
                            for (var i=0 ; i<checkStatus.data.length; i++){
                                ids[i]=checkStatus.data[i].id;
                            }
                            $.ajax({
                                url:"/deleteAdminUser?ids="+ids,
                                type:"delete",
                                success:function (msg) {
                                    if (msg.flag === "ok"){
                                        layer.msg("删除成功");
                                        //永远跳到第一页
                                        table.reload("demo"
                                            ,{page:{curr:1}}
                                        )
                                        return false;//关闭表单提交
                                    }else if(msg.flag === null){
                                        layer.msg("删除失败，请重试!!");
                                    }
                                }
                            })
                            break;
                        case 'insert':
                                //layerIndex:整个弹出层得对象
                                layerIndex = layer.open({
                                    type:1,// Page层类型
                                    area:['500px','330px'],
                                    title:["增加用户","padding-left:5px"], // 标题，及标题样式
                                    content:layui.$("#insertUserForm"), // 弹窗id
                                    shade:false //是否遮罩
                                })
                                //新增  找到lay-filter为addUserOk的表单
                                form.on("submit(addUserOk)",function (data) {
                                    console.log(data.field);//获取表单中的所有内容
                                    $.ajax({
                                        url:"/insertUser",
                                        type:"post",
                                        data: data.field,
                                        success:function (msg) {
                                            console.log(msg);
                                            layer.close(layerIndex)//提交之后关闭弹出层
                                            table.reload("demo")//刷新表单
                                            $("#insertForm")[0].reset();//清空弹窗
                                            return false;//关闭表单提交
                                        }
                                    });
                                })
                            break;
                    }
                });
                //搜索
                form.on("submit(search)",function (data) {
                    console.log(data.field);
                    table.reload("demo",{where:data.field})
                    return false;//关闭表单提交
                });
                //监听授权表单
                form.on('submit(updateRole)',function (data) {
                    // console.log(data.field);//拿到表单内的所有内容
                    var ids =[];
                    //为了防止覆盖，将值存在数组中
                    $('input[type=checkbox]:checked').each(function () {
                        ids.push($(this).val());
                    });
                    console.log(ids)
                    //携带userId和ids  清空再增加
                    $.ajax({
                        url: 'cleanAndInsertRoles',
                        data: "userId=" + data.field.userId + "&ids="+ ids,
                        success: function (ret) {
                            console.log(ret)
                        }
                    });
                    layer.closeAll();
                    return false;
                })
            });
        </script>
    </div>
</div>

<!--弹出新增的表单-->
<div class="site-text" style="margin-top: 10px ; display: none" id="insertUserForm" >
    <form class="layui-form" lay-filter="returnForm" id="insertForm">
        <div class="layui-form-item" style="display: none">
            <div class="layui-input-block">
                <input type="text" name="id" required  lay-verify="text" placeholder="请输入账号" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">邮箱</label>
            <div class="layui-input-block">
                <input type="text" name="email" lay-verify="text" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-block" >
                <input type="text" name="password" lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">真实姓名</label>
            <div class="layui-input-block">
                <input type="text" name="real_name" lay-verify="required" placeholder="请输入真实姓名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">单选框</label>
            <div class="layui-input-block">
                <input type="radio" name="status" value="0" title="无效">
                <input type="radio" name="status" value="1" title="有效" checked>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" lay-submit lay-filter="addUserOk">确定</button>
            </div>
        </div>
    </form>
</div>

<!--弹出授权表单-->
<div  style="padding:20px; display: none" id="giveRoleForm">
    <form class="layui-form">
        <input type="hidden" name="userId" id="userId_updateRole">
        <div class="layui-form-item">
            <div class="layui-inline" id="forEachRoles"><!--遍历拼接的时候要用到这个id-->
<!--                <div class="layui-input-block" style="margin:0 50px;">-->
<!--                    <input type="checkbox" name="" title="写作" checked>-->
<!--                </div>-->
<!--                <div class="layui-input-block" style="margin:0 50px;">-->
<!--                    <input type="checkbox" name="" title="发呆">-->
<!--                </div>-->
                <!--先写好静态的，然后再拼接格式-->
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-inline" style="float: right;width: 230px">
                <button type="button" class="layui-btn layui-btn-danger" lay-submit lay-filter="updateRole">立即提交</button>
            </div>
        </div>
    </form>
</div>

